﻿using UnityEngine;
using System.Collections.Generic;
using System.Collections;


public class QuadTitle : MonoBehaviour
{
    public UIAtlas titles;

    [SerializeField]
    [HideInInspector]
    public float x, y, width, height;

    float Round(float f)
    {
        float temp = f * 100;
        return Mathf.Round(temp) / 100;
    }

    public void SetSpriteFormAtlas(string name)
    {
        float factor = 0.005f;

        float textureWidth = titles.texture.width;
        float textureHeight = titles.texture.height;
        UISpriteData s = titles.GetSprite(name);
        x = s.x / textureWidth;
        y = (textureHeight - s.y - s.height) / textureHeight;
        width = s.width / textureWidth;
        height = s.height / textureHeight;
        MeshFilter mf = GetComponent<MeshFilter>();
#if UNITY_EDITOR
        for (int i = 0; i < mf.mesh.triangles.Length; ++i)
        {
            Debug.Log("triangles " + i + " " + mf.mesh.triangles[i] + " v:" + mf.mesh.vertices[mf.mesh.triangles[i]]
                + " uv: " + mf.mesh.uv[mf.mesh.triangles[i]]);
        }
#endif
        var vs = mf.mesh.vertices;
        float w = s.width * factor;
        float h = s.height * factor;
        vs[0] = new Vector3(-w, -h, 0);
        vs[1] = new Vector3(w, h, 0);
        vs[2] = new Vector3(w, -h, 0);
        vs[3] = new Vector3(-w, h, 0);
        mf.mesh.vertices = vs;

        var uvs = mf.mesh.uv;
        uvs[0] = new Vector2(x, y);
        uvs[1] = new Vector2(x + width, y + height);
        uvs[2] = new Vector2(x + width, y);
        uvs[3] = new Vector2(x, y + height);
        mf.mesh.uv = uvs;
    }
}
